package com.ruoyi.task.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.task.domain.TaskTemplate;
import com.ruoyi.task.domain.TaskUser;
import com.ruoyi.task.domain.WeChatTemplate;
import com.ruoyi.task.domain.WeiXinResponse;
import com.ruoyi.task.mapper.TaskTemplateMapper;
import com.ruoyi.task.service.ITaskTemplateService;
import com.ruoyi.task.service.ITaskUserService;
import com.ruoyi.task.service.WxAuthenticationService;
import javafx.concurrent.Task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


/**
 * 模版Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-26
 */
@Service
@Slf4j
public class TaskTemplateServiceImpl implements ITaskTemplateService
{
    @Autowired
    private TaskTemplateMapper taskTemplateMapper;

    @Autowired
    private ITaskUserService taskUserService;

    @Autowired
    private WxAuthenticationService wxAuthenticationService;

    @Value("${wx.templateid}")
    private String templateid;


    /**
     * 查询模版
     * 
     * @param id 模版主键
     * @return 模版
     */
    @Override
    public TaskTemplate selectTaskTemplateById(Long id)
    {
        return taskTemplateMapper.selectTaskTemplateById(id);
    }

    /**
     * 查询模版列表
     * 
     * @param taskTemplate 模版
     * @return 模版
     */
    @Override
    public List<TaskTemplate> selectTaskTemplateList(TaskTemplate taskTemplate)
    {
        return taskTemplateMapper.selectTaskTemplateList(taskTemplate);
    }

    private static final Map<String, Boolean> userFirstTimeMap = new ConcurrentHashMap<>();

    /**
     * 新增模版
     * 
     * @param taskTemplate 模版
     * @return 结果
     */
    @Override
    // 静态变量，用于标记是否是第一次执行
    public int insertTaskTemplate(TaskTemplate taskTemplate)
    {
        log.info("开始执行了------");
       // String token = wxAuthenticationService.getAccessToken();
        String token = null;
        try {
            token = getAccessToken();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (taskTemplate.getCreateTime() == null){
            taskTemplate.setCreateTime(DateUtils.getNowDate());
        }
        if (StringUtils.isNotEmpty(token)){
            token =  wxAuthenticationService.getAccessToken();
        }
        System.out.println("token===>"+token);
        try {
            sendMessage(token);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<TaskUser> list =  taskUserService.selectTaskUser(null);
        for (TaskUser taskUser : list) {
            String openId = taskUser.getOpenId();
            if (StringUtils.isNotEmpty(openId)){
                Map<String, WxAuthenticationService.TemplateDataValue> data = new HashMap<>(3);
                data.put("keyword1", new WxAuthenticationService.TemplateDataValue(taskTemplate.getTitle(), "#FF0000"));
                data.put("keyword2", new WxAuthenticationService.TemplateDataValue(taskTemplate.getAmount().toString()));
                data.put("keyword3", new WxAuthenticationService.TemplateDataValue(DateUtils.getTime()));
                WxAuthenticationService.TemplateMessage message = WxAuthenticationService.TemplateMessage.builder()
                        .touser(openId)
                        .templateId(templateid)
                        .data(data)
                        .build();
                // 获取当前用户的首次执行状态，若不存在则初始化为 true
                boolean isUserFirstTime = userFirstTimeMap.computeIfAbsent(openId, k -> true);
                if (isUserFirstTime) {
                    try {
                        // 第一次同步执行

                       WxAuthenticationService.WxTemplateResult wxTemplateResult = wxAuthenticationService.sendTemplateMessage(token, message);
                       log.info("wxTemplateResult:{}",wxTemplateResult);
                       taskTemplate.setStatus("1");
                        // 更新用户首次执行状态为 false
                        userFirstTimeMap.put(openId, false);
                    } catch (Exception e) {
                        // 处理同步执行时的异常
                        e.printStackTrace();
                    }
                } else {
                    // 后续异步执行
                    String finalToken = token;
                    new Thread(() -> {
                        try {
                            WxAuthenticationService.WxTemplateResult wxTemplateResult =    wxAuthenticationService.sendTemplateMessage(finalToken, message);
                            log.info("wxTemplateResult:{}",wxTemplateResult);
                        } catch (Exception e) {
                            // 处理异步执行时的异常
                            e.printStackTrace();
                        }
                    }).start();
                }
            }
        }
        return taskTemplateMapper.insertTaskTemplate(taskTemplate);
    }

    private final RestTemplate restTemplate = new RestTemplate();
    public void sendMessage(String accessToken) throws IOException {
        WeChatTemplate weChatTemplate = new WeChatTemplate();
        // 设置模板id
        weChatTemplate.setTemplateId("lmO3V5QyktsuZ-2czsvwG7LBLocpU29nRHoZ1Y26NBs");

        // 设置接收用户openId，这里填接收者的openid
        weChatTemplate.setToUser("oW3ay7c6WrXS9bKdLIUQIleRQAOs");
        //点击详情跳转的地址
        /**
         * 设置模板data参数
         * {{keyword1.DATA}}
         */
        weChatTemplate.getData().put("time3", WeChatTemplate.initData("2022-10-23 14:23:26","#459ae9"));//申请时间
        weChatTemplate.getData().put("thing1", WeChatTemplate.initData("张三","#459ae9"));//客户姓名
        weChatTemplate.getData().put("remark", WeChatTemplate.initData("如遇错误，请往当地社区服务中心进行解决。感谢您的使用！","#383838"));


        if(accessToken != null){
            // 发送消息的接口
            String pust_message_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
            //调用微信接口，发送模板消息
            WeiXinResponse result = restTemplate.postForObject(String.format(pust_message_url, accessToken),
                    weChatTemplate, WeiXinResponse.class);
            System.out.println("==========发送结果======="+result.toString());
            if (result.getErrcode() == 0){;
                System.out.println("==========成功"+result);
            }else{
                System.out.println("==========发送失败");
            }
        }else{
            System.out.println("==========失败");
        }


    }

    public String getAccessToken() throws IOException {
        try {
            String appid = "wx75224805df5d934a";//填写公众号的appid
            String secret = "bb1dffb707917979090b51172b81c796";//填写公众号的开发者密码(AppSecret)
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;

            StringBuilder json = new StringBuilder();
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
            JSONObject object = (JSONObject) JSONObject.parse(String.valueOf(json));
            String access_token = object.getString("access_token");

            if (access_token  != null) {
                System.out.println("=====access_token========"+access_token+"=============");
                return access_token;
            }
            return null;
        } catch (Exception e) {
            //log.error("获取accessToken异常" + e.getMessage());
            return null;
        }
    }

   /* public int insertTaskTemplate(TaskTemplate taskTemplate)
    {
        String token = wxAuthenticationService.getAccessToken();
        if (taskTemplate.getCreateTime() == null){
            taskTemplate.setCreateTime(DateUtils.getNowDate());
        }
        List<TaskUser> list =  taskUserService.selectTaskUserList(null);
        list.stream().forEach(taskUser -> {
           String openId = taskUser.getOpenId();
           if (StringUtils.isNotEmpty(openId)){
               Map<String, WxAuthenticationService.TemplateDataValue> data = new HashMap<>();
               data.put("keyword1", new WxAuthenticationService.TemplateDataValue(taskTemplate.getTitle(), "#FF0000"));
               data.put("keyword2", new WxAuthenticationService.TemplateDataValue(taskTemplate.getAmount().toString()));
               data.put("keyword3", new WxAuthenticationService.TemplateDataValue(DateUtils.getTime()));
               WxAuthenticationService.TemplateMessage message = WxAuthenticationService.TemplateMessage.builder()
                       .touser(openId)
                       .templateId("TEMPLATE_ID")
                       .data(data)
                       .build();
               WxAuthenticationService.WxTemplateResult  wxTemplateResult = wxAuthenticationService.sendTemplateMessage(token,message);

           }
        });
        return taskTemplateMapper.insertTaskTemplate(taskTemplate);
    }*/

    /**
     * 修改模版
     * 
     * @param taskTemplate 模版
     * @return 结果
     */
    @Override
    public int updateTaskTemplate(TaskTemplate taskTemplate)
    {
        return taskTemplateMapper.updateTaskTemplate(taskTemplate);
    }

    /**
     * 批量删除模版
     * 
     * @param ids 需要删除的模版主键
     * @return 结果
     */
    @Override
    public int deleteTaskTemplateByIds(Long[] ids)
    {
        return taskTemplateMapper.deleteTaskTemplateByIds(ids);
    }

    /**
     * 删除模版信息
     * 
     * @param id 模版主键
     * @return 结果
     */
    @Override
    public int deleteTaskTemplateById(Long id)
    {
        return taskTemplateMapper.deleteTaskTemplateById(id);
    }
}
